package com.wulin.wucut.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.wulin.wucut.common.SuffixConstant;
import com.wulin.wucut.domain.entity.draft.meta.info.DraftMetaInfo;
import com.wulin.wucut.domain.request.CreatDraftMetaInfoRequest;
import com.wulin.wucut.enums.WuLinExceptionEnum;
import com.wulin.wucut.exception.WuLinException;
import com.wulin.wucut.service.DraftService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static com.wulin.wucut.common.JianYinConstant.DRAFT_META_INFO;

@Service
@Slf4j
public class DraftServiceImpl implements DraftService {
    @Value("${jianyin.draft.directory}")
    private String draftDirectory;
    @Override
    public void createDraft(CreatDraftMetaInfoRequest request) throws IOException {
        String draftName = request.getDraftName();
        String draftFilePath = draftDirectory + "/" + draftName+"/"+DRAFT_META_INFO+ SuffixConstant.JSON;
        if (FileUtil.exist(draftFilePath)) {
            throw new WuLinException(WuLinExceptionEnum.FILE_ALREADY_EXISTS);
        }
        File file = FileUtil.touch(draftFilePath);
        //创建写入
        DraftMetaInfo metaInfo = new DraftMetaInfo();
        metaInfo.setDraftFoldPath(draftFilePath);
        BufferedWriter writer = FileUtil.getWriter(file, StandardCharsets.UTF_8, false);
        String metaInfoJson = JSONObject.toJSONString(metaInfo);
        writer.write(metaInfoJson);
        writer.flush();
        log.info("创建{}成功，创建地址：{}",draftName,draftFilePath);
    }
    
    
}
